package com.dcbeida.activity;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dcbeida.LoadingActivity;
import com.dcbeida.MyApplication;
import com.dcbeida.R;
import com.dcbeida.db.AreaDB;
import com.dcbeida.fragment.BaseFragment;
import com.dcbeida.fragment.Home2Fragment;
import com.dcbeida.fragment.HomeFragment;
import com.dcbeida.fragment.MineFragment;
import com.dcbeida.fragment.SalsesFragment;
import com.dcbeida.fragment.StockFragment;
import com.dcbeida.utils.Constants;
import com.dcbeida.utils.SharedPreferencesUtils;
import com.dcbeida.utils.Utils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

/**
 * 首页
 * Created by swt on 2016/11/17.
 * test
 */
public class HomeActivity extends BaseActivity implements OnClickListener {


    LinearLayout lin_left;
    ImageView iv_tmd;

    //bottombar
    private LinearLayout tab1;
    private LinearLayout tab2;
    private LinearLayout tab4;
    private ImageView ivTab1;
    private TextView tvTab1;

    private ImageView ivTab2;
    private TextView tvTab2;

    private ImageView ivTab4;
    private TextView tvTab4;

    private View bottom1;


    SharedPreferencesUtils sp;
    private Home2Fragment mHomeFragment;
    private SalsesFragment mSalsesFragment;
    private StockFragment mStockFragment;
    private LinearLayout tab3;
    private ImageView ivTab3;
    private TextView tvTab3;
    private MineFragment mMineFragment;


    private ObjectAnimator leftAnimator;
    private ObjectAnimator alphaAnimator;

    private boolean isAnimIng = false;
    private boolean isRevser = false;

    private Runnable animRunable;


    private MainBroadcastReceiver mainBroadcastReceiver;


    @Override
    protected int getLayoutResId() {
        return R.layout.home_btn;
    }


    private class MainBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case Constants.RECEIVER_HOME_FRESH:
                    mHomeFragment.reFresh();
                    break;
                case Constants.RECEIVER_SALE_FRESH:
                    if (mSalsesFragment != null)
                        mSalsesFragment.reFresh();
                    break;
                case Constants.RECEIVER_STOCK_FRESH:
                    mStockFragment.reFresh();
                    break;
            }
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        readCityDB();
        sp = SharedPreferencesUtils.getInstance(this);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.RECEIVER_HOME_FRESH);
        intentFilter.addAction(Constants.RECEIVER_SALE_FRESH);
        intentFilter.addAction(Constants.RECEIVER_STOCK_FRESH);
        mainBroadcastReceiver = new MainBroadcastReceiver();
        registerReceiver(mainBroadcastReceiver, intentFilter);


        setupView();
        changeTab(0);

        initAnimator();

    }


    public View getLeftView() {
        return lin_left;
    }


    private void initAnimator() {
        leftAnimator = ObjectAnimator.ofFloat(lin_left, "translationX",
                (float) Utils.convertDip2Pixel(250), 0f);
        leftAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
        leftAnimator.addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                isAnimIng = true;

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                isAnimIng = false;
                if (animRunable != null)
                    animRunable.run();
                animRunable = null;
            }
        });
        leftAnimator.setDuration(400);
        alphaAnimator = ObjectAnimator.ofFloat(iv_tmd, "alpha", 0, 0.4f);
        alphaAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
        alphaAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                if (!isRevser)
                    iv_tmd.setVisibility(View.VISIBLE);

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                if (isRevser)
                    iv_tmd.setVisibility(View.GONE);
            }
        });
        alphaAnimator.setDuration(400);

    }

    public void startAnim() {
        if (isAnimIng)
            return;
        isRevser = false;
        leftAnimator.start();
        alphaAnimator.start();
    }

    public void goBackAnim(Runnable runnable) {
        if (isAnimIng)
            return;
        isRevser = true;
        this.animRunable = runnable;
        leftAnimator.reverse();
        alphaAnimator.reverse();
    }


    private void readCityDB() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                AreaDB areaDB = new AreaDB(HomeActivity.this);
                Constants.provinces = areaDB.getProvinces();
                Constants.allCities = areaDB.getAllCities();
                Constants.areas = areaDB.getAllAreas();
            }
        }).start();
    }

    /**
     * 初始化控件
     */
    private void setupView() {
        //bottombar
        tab1 = (LinearLayout) findViewById(R.id.tab1);
        tab2 = (LinearLayout) findViewById(R.id.tab2);
        tab3 = (LinearLayout) findViewById(R.id.tab3);
        tab4 = (LinearLayout) findViewById(R.id.tab4);
        tab1.setOnClickListener(this);
        tab2.setOnClickListener(this);
        tab3.setOnClickListener(this);
        tab4.setOnClickListener(this);

        ivTab1 = (ImageView) findViewById(R.id.ivTab1);
        tvTab1 = (TextView) findViewById(R.id.tvTab1);
        ivTab2 = (ImageView) findViewById(R.id.ivTab2);
        tvTab2 = (TextView) findViewById(R.id.tvTab2);
        ivTab3 = (ImageView) findViewById(R.id.ivTab3);
        tvTab3 = (TextView) findViewById(R.id.tvTab3);
        ivTab4 = (ImageView) findViewById(R.id.ivTab4);
        tvTab4 = (TextView) findViewById(R.id.tvTab4);

        bottom1 = findViewById(R.id.bottom1);

        lin_left = (LinearLayout) findViewById(R.id.lin_left);
        iv_tmd = (ImageView) findViewById(R.id.iv_tmd);

        iv_tmd.setOnClickListener(this);

    }


    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
            case R.id.iv_tmd:
                goBackAnim(null);
                break;

            case R.id.tab1:
                changeTab(0);
                break;

            case R.id.tab2:
                changeTab(1);
                break;

            case R.id.tab3:
                changeTab(2);
                break;

            case R.id.tab4:
                changeTab(3);
                break;

            default:
                break;
        }
    }

    private int currentTab = -1;

    private void changeTab(int tab) {
        if (currentTab != tab) {
            setbottombcdefail();
            switch (tab) {
                case 0:
                    ivTab1.setImageResource(R.drawable.home_press);
                    tvTab1.setTextAppearance(this, R.style.TextAppear_Theme_c_0C87EA_Size12);
                    break;
                case 1:
                    ivTab2.setImageResource(R.drawable.xiaoshou_press);
                    tvTab2.setTextAppearance(this, R.style.TextAppear_Theme_c_0C87EA_Size12);
                    break;
                case 2:
                    ivTab3.setImageResource(R.drawable.kucun_press);
                    tvTab3.setTextAppearance(this, R.style.TextAppear_Theme_c_0C87EA_Size12);
                    break;
                case 3:
                    ivTab4.setImageResource(R.drawable.my_press);
                    tvTab4.setTextAppearance(this, R.style.TextAppear_Theme_c_0C87EA_Size12);
                    break;


                default:
                    break;
            }
            setTabSelection(tab);
            currentTab = tab;
        }
    }

    private void setbottombcdefail() {
        ivTab1.setImageResource(R.drawable.home_nomal);
        ivTab2.setImageResource(R.drawable.xiaoshou_nomal);
        ivTab3.setImageResource(R.drawable.kucun_nomal);
        ivTab4.setImageResource(R.drawable.my_nomal);
        tvTab1.setTextAppearance(this, R.style.TextAppear_Theme_c_666666_Size12);
        tvTab2.setTextAppearance(this, R.style.TextAppear_Theme_c_666666_Size12);
        tvTab3.setTextAppearance(this, R.style.TextAppear_Theme_c_666666_Size12);
        tvTab4.setTextAppearance(this, R.style.TextAppear_Theme_c_666666_Size12);
    }

    private List<BaseFragment> baseFragments = new ArrayList<>();

    private void setTabSelection(int index) {
        // 开启一个Fragment事务

        FragmentTransaction transaction = obtainFragmentTransaction(index);
        // 先隐藏掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
        hideFragments(transaction);
        switch (index) {
            case 0:
                if (mHomeFragment == null) {
                    // 如果MessageFragment为空，则创建一个并添加到界面上
                    mHomeFragment = new Home2Fragment();
                    baseFragments.add(mHomeFragment);
                    transaction.add(R.id.tab_content, mHomeFragment, Home2Fragment.class.getName());
                } else {
                    // 如果MessageFragment不为空，则直接将它显示出来
                    transaction.show(mHomeFragment);
                }
                break;
            case 1:
                // 当点击了消息tab时，改变控件的图片和文字颜色
                if (mSalsesFragment == null) {
                    // 如果MessageFragment为空，则创建一个并添加到界面上
                    mSalsesFragment = new SalsesFragment();
                    baseFragments.add(mSalsesFragment);
                    transaction.add(R.id.tab_content, mSalsesFragment, SalsesFragment.class.getName());
                } else {
                    // 如果MessageFragment不为空，则直接将它显示出来
                    transaction.show(mSalsesFragment);
                }
                break;
            case 2:

                if (mStockFragment == null) {
                    // 如果MessageFragment为空，则创建一个并添加到界面上
                    mStockFragment = new StockFragment();
                    baseFragments.add(mStockFragment);
                    transaction.add(R.id.tab_content, mStockFragment, StockFragment.class.getName());
                } else {
                    // 如果MessageFragment不为空，则直接将它显示出来
                    transaction.show(mStockFragment);
                }

                break;
            case 3:
                // 当点击了消息tab时，改变控件的图片和文字颜色
                if (mMineFragment == null) {
                    // 如果MessageFragment为空，则创建一个并添加到界面上
                    mMineFragment = new MineFragment();
                    baseFragments.add(mMineFragment);
                    transaction.add(R.id.tab_content, mMineFragment, MineFragment.class.getName());
                } else {
                    // 如果MessageFragment不为空，则直接将它显示出来
                    transaction.show(mMineFragment);
                }
                break;
        }
        transaction.commit();
    }

    private FragmentTransaction obtainFragmentTransaction(int index) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        // 设置切换动画
        //        if (index > currentTab) {
        //            ft.setCustomAnimations(R.anim.slide_left_in, R.anim.slide_left_out2);
        //        } else {
        //            ft.setCustomAnimations(R.anim.slide_right_in2, R.anim.slide_right_out);
        //        }
        return ft;
    }

    /**
     * 将所有的Fragment都置为隐藏状态。
     *
     * @param transaction 用于对Fragment执行操作的事务
     */
    private void hideFragments(FragmentTransaction transaction) {
        if (mHomeFragment != null) {
            transaction.hide(mHomeFragment);
        }
        if (mSalsesFragment != null) {
            transaction.hide(mSalsesFragment);
        }
        if (mStockFragment != null) {
            transaction.hide(mStockFragment);
        }
        if (mMineFragment != null) {
            transaction.hide(mMineFragment);
        }

    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        unregisterReceiver(mainBroadcastReceiver);

    }

    /**
     * 实现再按一次退出提醒
     */
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 3000) {
                Toast.makeText(HomeActivity.this, R.string.snack_exit_once_more, Toast.LENGTH_LONG).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                android.os.Process.killProcess(android.os.Process.myPid());
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


}